package com.pengli.mytools.retrofit;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class ServiceGenerator {

    private static String apiBaseUrl = NetConstant.tokenBaseUrl;

    private static Retrofit retrofit;

    private static Retrofit.Builder builder =
            new Retrofit.Builder()
                    .baseUrl(apiBaseUrl)
                    .addConverterFactory(GsonConverterFactory.create());

    private static OkHttpClient.Builder httpClient =
            new OkHttpClient.Builder();


    private static HttpLoggingInterceptor logging =
            new HttpLoggingInterceptor()
                    .setLevel(HttpLoggingInterceptor.Level.BODY);

    public static void changeApiBaseUrl(String newApiBaseUrl) {
        apiBaseUrl = newApiBaseUrl;
        builder = new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl(apiBaseUrl);
    }

    public static <S> S createService(Class<S> serviceClass) {
        if (!httpClient.interceptors().contains(logging)) {
            httpClient.addInterceptor(logging);
        }
//        httpClient.addInterceptor(new ReceivedCookiesInterceptor());
//        httpClient.addInterceptor(new AddCookiesInterceptor());
        retrofit = builder.client(httpClient.build()).build();
        return retrofit.create(serviceClass);
    }
//    public static <S> S createService(Class<S> serviceClass, AccessToken token) {
//        String authToken = token.getTokenType().concat(token.getAccessToken());
//        return createService(serviceClass, authToken);
//    }
}